import type { ResponseStructure } from '@/typings/request';
import type { RequestOptions } from '@@/plugin-request/request';
import type { RequestConfig } from '@umijs/max';
import { Toast } from 'antd-mobile';
import Cookies from 'js-cookie';

// 运行时配置
export const RequestErrorConfig: RequestConfig = {
  // 统一的请求设定
  // timeout: 1000,
  // headers: {'X-Requested-With': 'XMLHttpRequest'},

  // 请求拦截器
  requestInterceptors: [
    (config: RequestOptions) => {
      // 拦截请求配置，进行个性化处理。

      // 添加请求统一前缀
      const prefix: string = process.env.API_URL ? process.env.API_URL : '';
      console.log('prefix7878', prefix);
      let { url } = config;
      // console.log('url', url, prefix)  // /api/v1/queryUserList
      if (url && !url.startsWith(prefix)) {
        url = `${prefix}${url}`;
      }
      // 添加token
      const token = Cookies.get('vue_admin_template_token'); // localStorage.getItem('token');
      const defaultToken =
        'eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX2tleSI6IjRkYTNjOTZlLTg5MDItNGMxNy1iNzIzLTU5MGRjYzhmODY5ZCIsInVzZXJuYW1lIjoiYWRtaW4ifQ.MOPZmmum-MntpcgbPQiejZnakuup-_Rq5PEVZCGza1yMOZQyA5E40pmvzs2w2S9Aird98tgS3iTwXQuHzPd-yg';
      // console.log('token11', token);
      config.headers = {
        ...config.headers,
        // Authorization: `Bearer ${token}`,
        Authorization: token ?? defaultToken,
      };
      return { ...config, url };
    },
  ],

  // 响应拦截器
  responseInterceptors: [
    (response) => {
      // 拦截响应数据，进行个性化处理
      const { data } = response;
      const { rMsg, rCode } = data as unknown as ResponseStructure;
      if (rCode !== 200) {
        Toast.show(rMsg || '请求失败！');
        return Promise.reject(response);
      } else {
        return response;
      }
      // return response;
    },
  ],
};
